import bearerAuth from "@fastify/bearer-auth";
import auth from "@fastify/auth";
import fp from "fastify-plugin";
import { User } from "../models/user";
function authPlugin(app, opt, next) {
  app
    .register(auth)
    .register(bearerAuth, {
      addHook: false,
    })
    .addHook("onRequest", async (req, rep) => {
      if (req.routeOptions.config.allowGuest) {
        return;
      }
      const { authorization } = req.raw.headers;
      const onErr = (err) => {
        rep.statusCode = 401;
        throw new Error("请先登录");
      };

      if (authorization) {
        const token = authorization.replace("Bearer", "").trim();

        const user = await app.cache.get(token).catch(onErr);

        if (!user) {
          onErr();
        } else {
          req.getUser = async (cache = true) => {
            if (cache) return user;
            return User.findOne({ name: user.name });
          };
          req.user = user;
        }
      } else {
        onErr();
      }
    })
    .addHook("preSerialization", function (req, rep, payload, done) {
      done(null, {
        code: rep.statusCode === 200 ? 0 : rep.statusCode,
        data: payload,
      });
    });

  next();
}

export default fp(authPlugin);
